package com.pimwi.service
{
  import com.pimwi.dp.GroupDP;
  import com.pimwi.model.ModelLocator;
  import com.pimwi.vo.Group;
  import com.pimwi.vo.request.SaveGroupRequest;
  
  import mx.collections.ArrayCollection;
  import mx.controls.Alert;
  import mx.rpc.events.ResultEvent;
  
  public class GroupService extends BaseService
  {
    public function GroupService()
    {
      super();
    }

    /******************/
    /** SAVE GROUP **/
    /******************/

    public function saveGroup(request:SaveGroupRequest):void
    {
      _service.saveGroup.addEventListener(ResultEvent.RESULT, saveGroupResultHandler);
      _service.saveGroup(request);
    }

    private function saveGroupResultHandler(event:ResultEvent):void
    {
      _service.saveGroup.removeEventListener(ResultEvent.RESULT, saveGroupResultHandler);

      var response:Object = event.result;
      if (response.errorMessage != "")
      {
        Alert.show(response.errorMessage, "Erreur");
      }
      else
      {
        updateUserGroups(response.userGroups);
      }
    }

    /*************/
    /** PRIVATE **/
    /*************/

    private function updateUserGroups(retrievedGroups:ArrayCollection):void // list of Group
    {
      var locator:ModelLocator = ModelLocator.getInstance();
      var proxy:Object = null;
      var userGroups:ArrayCollection = new ArrayCollection(); // list of GroupDP
      var group:Group = null;

      group = new Group(0, 0, "N/A");
      userGroups.addItemAt(new GroupDP(group), 0);

      for each (proxy in retrievedGroups)
      {
        group = new Group(proxy.id, proxy.userId, proxy.name);
        var groupDP:GroupDP = new GroupDP(group);
        userGroups.addItem(groupDP);
      }
      locator.userGroups = userGroups;

      var allGroupsFilter:Group = new Group(-1, 0, "Tous");
      var filterGroups:ArrayCollection = new ArrayCollection();
      filterGroups.addItem(new GroupDP(allGroupsFilter));
      
      for each (var _groupDP:GroupDP in userGroups)
      {
        filterGroups.addItem(_groupDP);
      }
      locator.filterGroups = filterGroups;
    }

  }
}